import React, { useEffect, useState } from "react";
import { Breadcrumb, Table, message, Image, Button } from "antd";
// import axios from "axios";

// import requestGet from "../../../utils/request";

import { getBannerList, removeBannerItem } from "../../../api/index";

const Index = () => {
  const [messageApi, contextHolder] = message.useMessage();
  // 为了是dataSource有响应式，只能用useState来定义
  const [dataSource, setDataSource] = useState([]);

  // 列信息
  const columns = [
    {
      title: "图片",
      dataIndex: "img",
      render(text) {
        return <Image src={text} alt="" style={{ width: 140, height: 140 }} />;
      },
    },
    {
      title: "链接",
      dataIndex: "link",
      // 没有render的时候，默认是直接字符串显示
      // render可以通过return自己去显示标签
      // 有一个参数就是原本应该显示的字符串
      render(text) {
        return <span>{text}</span>;
      },
    },
    {
      title: "提示",
      dataIndex: "alt",
    },
    {
      title: "操作",
      // dataIndex: "bannerid",
      // 第二个参数record表示的是一整行数据
      // 删除功能最好添加二次确认
      render(text, record) {
        return (
          // <Button
          //   type="primary"
          //   danger
          //   onClick={() => removeItem(record.bannerid)}
          // >
          //   删除
          // </Button>
          // <Popconfirm
          //   title="删除"
          //   description="你确定要删除这条记录吗?"
          //   onConfirm={() => removeItem(record.bannerid)}
          //   okText="是"
          //   cancelText="否"
          // >
          <Button
            type="primary"
            danger
            onClick={() => removeItem(record.bannerid)}
          >
            删除
          </Button>
          // </Popconfirm>
        );
      },
    },
  ];

  const removeItem = (id) => {
    removeBannerItem({ bannerid: id }).then((res) => {
      if (res) {
        messageApi.open({
          type: "success",
          content: "删除成功",
        });
        getData();
      }
    });
  };

  const getData = () => {
    getBannerList().then((res) => {
      res && setDataSource(res.data);
    });
  };

  useEffect(() => {
    getData();
    // eslint-disable-next-line
  }, []);

  return (
    <div>
      {contextHolder}
      <Breadcrumb
        style={{ marginBottom: 20 }}
        items={[
          {
            title: "轮播图管理",
          },
          {
            title: "轮播图列表",
          },
        ]}
      />

      {/* dataSource是表格数据 */}
      {/* columns是列信息 */}
      {/* rowKey防止报错，将数据的bannerid属性作为唯一的标识 */}
      <Table dataSource={dataSource} columns={columns} rowKey="bannerid" />
    </div>
  );
};

export default Index;
